package cn.gzsxt.music.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.gzsxt.music.service.PowerService;

//检查权限工具类
@Component
public class PermissionUtil {
	
	
	private static HttpSession session;
	
	//注入权限的service
	private static PowerService powerService;
	
	/**
	 * 检查当前登录用户的权限集合是否包含请求资源
	 * @param uri 请求资源 如 admin/addAdmin.do, role/roleLost.do , index.getMenu.do
	 * @return 包含 返回 true  不包含 返回false
	 */
	public static boolean checkPermission(String uri) {
		
		//1.获取HttpSesion种共享的用户和角色信息
		Map<String, Object> user = (Map<String, Object>) session.getAttribute(ConstantUtil.USER_IN_SESSION);
		Map<String, Object> role = (Map<String, Object>) session.getAttribute(ConstantUtil.ROLE_IN_SESSION);
		
		//超级管理员 放行
		if("admin".equals(user.get("admin_name"))) {
			return true;
		}
		if (uri.contains("index")) {
			return true;
		}

		List<Map<String, Object>> allPowers = powerService.getAllPowers();
		
		List<String> powerActions = new ArrayList<>();
		//2.循环所有的权限
		for (Map<String, Object> power : allPowers) {
			//2.1获取每个权限的power_action   : admin/addAdmin.do, role/roleLost.do ....
			String power_action = (String) power.get("power_action");
			powerActions.add(power_action);
		}
		//判断用户请求的资源是否和 power_action相等,相等,在做判断,不相等,说明此请求不需要拦截,放行
		if(powerActions.contains(uri)) {
			//非超级管理员的请求都需要判断
			//获取当前登录用户的角色中所有的权限
			String role_action = (String) role.get("role_action");
			//判断角色action中是否包含请求资源, 主页面要放行,获取菜单请求要放行
			if(role_action.contains(uri)) {
				return true;
			}
		}
		return false;
	}
	
	@Autowired
	public void setPowerService(PowerService powerService) {
		PermissionUtil.powerService = powerService;
	}
	
	//自动注入 setter方法注入
	@Autowired
	public void setSession(HttpSession session) {
		PermissionUtil.session = session;
	}
}
